package com.my.socket.nio.v8;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;

/**
 * Created by Scarlett on 2018/7/2 0002.
 */
public class SocketWriteHandler extends SocketHandler {

    private int BLOCK = 4096;
    private ByteBuffer sendBuffer = ByteBuffer.allocate(BLOCK);
    private static int Index = 1;

    public SocketWriteHandler(ServerDispatcher dispatcher, ServerSocketChannel sc, Selector selector) throws IOException {
        super(dispatcher, sc, selector);
    }

    @Override
    public void runnerExecute(int readyKeyOps) throws IOException {
        if (readyKeyOps == SelectionKey.OP_WRITE) {
            LOGGER.debug("Server : Writable.");
            String data = String.format("%d", Index);
            byte[] req = data.getBytes();
            sendBuffer.clear();

            LOGGER.debug(String.format("Server : Write %s", data));

            sendBuffer = ByteBuffer.allocate(req.length);
            sendBuffer.put(req);
            sendBuffer.flip();
            socketChannel.write(sendBuffer);
            Index++;
            socketChannel.register(serverDispatcher.getReadSelector(), SelectionKey.OP_READ);
        }
    }

}
